//
//  MBBLEDeviceListViewController.m
//  mZero-iOS
//
//  Created by catch on 16/8/23.
//  Copyright © 2016年 Shenzhen Maker Works Technology Co., Ltd. All rights reserved.
//

#import "MBBLEDeviceListViewController.h"
#import "UIView+MB.h"
#import "BLECentralManager.h"
#import "MBBLEDeviceCell.h"
#import "MBUtils.h"
#import "NSArray+MB.h"
#import "MBMacros.h"

@interface MBBLEDeviceListViewController ()<UITableViewDelegate,UITableViewDataSource,BLEControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLab;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *refreshButton;
@property (nonatomic, strong) NSMutableArray<BLEPeripheral *> *deviceList;

@end

@implementation MBBLEDeviceListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.animationType = MBAlterAnimationScale;
    [self.mainView setLayerCornerRadius:2.0f];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_refreshButton setTitle:NSLocalizedString(@"ble_refresh_list", nil) forState:UIControlStateNormal];
    _refreshButton.titleLabel.font = MFont(IsPhone ? 15 :18);
    
    _titleLab.font = MFont(IsPhone ? 17 :20);
    
    
    [[BLECentralManager sharedManager] addDelegate:self];
    
    [self reload];
}

-(void)dealloc{
    [[BLECentralManager sharedManager] removeDelegate:self];
}

-(void)bleStateChanged:(NSInteger)state{
    if(state == BLECentralDelegateStateDiscoverPeripheral){
        [self reload];
    }
}

-(void)reload{
    self.deviceList = [NSMutableArray array];
    
    for (BLEPeripheral* peripheral in [BLECentralManager sharedManager].peripherals) {
        if ([peripheral.activePeripheral.name.lowercaseString hasPrefix:@"makeblock"]) {
            CGFloat distance = [peripheral distanceByRSSI];
            if (distance == -1.0f) {
                continue;
            }
            [self.deviceList addObject:peripheral];
        }
    }
    
    //排序
    if(self.deviceList.count>1){
        [self.deviceList sortUsingComparator:^NSComparisonResult(BLEPeripheral* obj1, BLEPeripheral* obj2){
            return [obj1 distanceByRSSI] > [obj2 distanceByRSSI];
        }];
    }
    [_tableView reloadData];
}

- (IBAction)refreshButtonClicked:(id)sender {
    [[BLECentralManager sharedManager] resetScanning];
}

#pragma mark -- UITableViewDelegate & UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _deviceList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *TableSampleIdentifier = @"MBBLEDeviceListViewControllerCell";
    MBBLEDeviceCell *cell = (MBBLEDeviceCell *)[tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MBBLEDeviceCell" owner:self options:nil]objectAtIndex:0];
    }
    
    BLEPeripheral* bean = [_deviceList safe_objectAtIndex:indexPath.row];
    if (bean) {
        [cell configureWithName:bean.displayName distance:bean.distanceByRSSI];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
    BLEPeripheral* bean = [_deviceList safe_objectAtIndex:indexPath.row];
    if (bean && _delegate && [_delegate respondsToSelector:@selector(didSelectPeripheral:)]) {
        [_delegate didSelectPeripheral:bean];
        [self dismissView];
    }
}

#pragma mark -- touch

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissView];
}

#pragma mark -- rotate

- (BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

@end
